package com.flying.ouyu.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ControllerManager {
	
	private static ControllerManager instance = new ControllerManager();
	
	public static ControllerManager getInstance()
	{
		return instance;
	}
	/**
	 * 控制器列表
	 */
	private Map<Class<?>,BaseController> controllerList = new HashMap<Class<?>,BaseController>();
	
	private ControllerManager()
	{
	}
	/**
	 * 注册控制器
	 * @param controller
	 * @param observerClass
	 */
	public void registerController(BaseController controller,Class<?> observerClass)
	{
		if (controller == null || observerClass == null)
			return;
		
		synchronized(controllerList)
		{
			if (!hasContainController(observerClass))
			{
				controllerList.put(observerClass, controller);
			}
		}
	}
	/**
	 * 卸载控制器
	 * @param observerClass
	 */
	public void unregisterController(Class<?> observerClass)
	{
		if (observerClass == null)
			return;
		
		synchronized(controllerList)
		{
			if (hasContainController(observerClass))
			{
				controllerList.remove(observerClass);
			}
		}
	}
	/**
	 * 根据观察者类型清除观察者
	 * @param observer
	 */
	public void unregisterObserver(IObserver observer)
	{
		if (observer == null)
			return;
		
		synchronized(controllerList)
		{
			for(Class<?> cClass : controllerList.keySet())
			{
				if (cClass == observer.getClass())
				{
					controllerList.get(cClass).unregisterObserver(observer);
				}
			}
		}
	}
	/**
	 * 清除观察者列表
	 * @param observerList
	 */
	public void clearObserver(List<IObserver> observerList)
	{
		if (observerList == null)
			return;
		
		for(IObserver observer:observerList)
		{
			unregisterObserver(observer);
		}
	}
	/**
	 * 是否已经注册
	 * @param observerClass
	 * @return
	 */
	private boolean hasContainController(Class<?> observerClass)
	{
		if (observerClass == null)
			return false;
		
		synchronized(controllerList)
		{
			return (controllerList.containsKey(observerClass));
		}
	}
}
